package com.yuexiang.melodyhub.authserver.controller;

import com.yuexiang.melodyhub.authserver.dto.OAuthLogin.param.OAuthLoginParam;
import com.yuexiang.melodyhub.authserver.dto.OAuthLogin.response.OAuthLoginResponse;
import com.yuexiang.melodyhub.authserver.dto.OAuthRegister.param.OAuthRegisterParam;
import com.yuexiang.melodyhub.authserver.handler.context.LoginContext;
import com.yuexiang.melodyhub.authserver.handler.context.RegisterContext;
import com.yuexiang.melodyhub.common.handler.AbstractValidationHandler;
import com.yuexiang.melodyhub.common.result.ResultData;
import com.yuexiang.melodyhub.common.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/oauth")
public class LoginController {

    @Autowired
    @Qualifier("loginValidationChain")
    private AbstractValidationHandler<LoginContext> loginChain;

    @Autowired
    @Qualifier("registerValidationChain")
    private AbstractValidationHandler<RegisterContext> registerChain;

    @PostMapping("/login")
    public ResultData<OAuthLoginResponse> login(@RequestBody OAuthLoginParam oauthLoginParam) {
        LoginContext context = new LoginContext(oauthLoginParam);
        loginChain.handler(context);
        return ResultData.success(new OAuthLoginResponse(context.getEmail(), context.getAvatar(), context.getToken(), JwtUtil.parseToken(context.getToken()).getPayload().getExpiration().getTime()));
    }

    @PostMapping("/register")
    public ResultData<?> register(@RequestBody OAuthRegisterParam oAuthRegisterParam) {
        RegisterContext context = new RegisterContext(oAuthRegisterParam);
        registerChain.handler(context);
        return ResultData.success(null);
    }

}
